//
// Created by Max on 2024/5/14.
//

#include <dirent.h>
#include "SaveFile.h"
#include "fstream"
#include "iostream"
#include "filesystem"

SaveFile::SaveFile() : mFile(nullptr), mFilePath("") {
    LOGE("SaveFile constructed!");
}

SaveFile::~SaveFile() {
    LOGI("SaveFile destructed!");
}

int SaveFile::openFile(std::string &filePath) {

    createFolder(filePath);
    mFilePath = filePath + "/haier.wav";
    mFile = fopen(mFilePath.c_str(), "wb");
    if (mFile == nullptr) {
        LOGE("openFile Failed");
        return -1;
    }
    LOGI("SaveFile openFile Success!");
    return 0;
}

int SaveFile::closeFile() {
    if (mFile == nullptr)
        return 0;
    return fclose(mFile);
}

int SaveFile::writeToFile(void *buff, uint32_t size, uint32_t count) {
    if (mFile == nullptr)
        return -1;
    return fwrite(buff, size, count, mFile);
}

int SaveFile::fSeekFile(long offset, int where) {
    if (mFile == nullptr)
        return -1;
    return fseek(mFile, offset, where);
}

int SaveFile::createFolder(std::string &folderPath) {

    if (!isFileExist(folderPath)) {
        std::filesystem::path path(folderPath);
        std::filesystem::create_directories(path);
    }
    return 0;
}

int SaveFile::isFileExist(std::string &folderPath) {

    std::ifstream ifStream(folderPath);
    return ifStream.good();
}

int SaveFile::countFilesInDirectory(const std::string &path) {
    int count = 0;
    DIR *dir = opendir(path.c_str());
    if (dir == nullptr) {
        std::cerr << "Failed to open directory" << std::endl;
        return 0;
    }
    struct dirent *entry;
    while ((entry = readdir(dir)) != nullptr) {
        if (entry->d_type == DT_REG) { // 确保是普通文件
            ++count;
        }
    }
    closedir(dir);
    return count;
}

